import request from '@/utils/request'
const BASE_URL = '/api/yyplatform/admin/layout/file/'

class FileAPI {
  static uploadUrl = import.meta.env.VITE_APP_BASE_API + '/api/yyplatform/admin/layout/file/upload'

  /**
   * 上传文件
   *
   * @param file
   */
  static upload(file: File) {
    const formData = new FormData()
    formData.append('file', file)
    return request<any, FileInfo>({
      url: `${BASE_URL}/upload`,
      method: 'post',
      data: formData,
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    })
  }

  /**
   * 下载文件
   * @param url
   * @param fileName
   */
  static downloadFile(url: string, fileName?: string) {
    return request({
      url: url,
      method: 'get',
      responseType: 'blob'
    }).then((res) => {
      const blob = new Blob([res.data])
      const a = document.createElement('a')
      const url = window.URL.createObjectURL(blob)
      a.href = url
      a.download = fileName || '下载文件'
      a.click()
      window.URL.revokeObjectURL(url)
    })
  }

  /**
   * 删除文件
   *
   * @param filePath 文件完整路径
   */
  static deleteByPath(filePath?: string) {
    return request({
      url: `${BASE_URL}/delete`,
      method: 'post',
      params: { filePath: filePath }
    })
  }
}
export default FileAPI

/**
 * 文件API类型声明
 */
export interface FileInfo {
  /** 文件名 */
  name: string
  /** 文件路径 */
  url: string
}
